<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200">
    <div v-loading="formLoading">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="t('interview.fields.batchId')" prop="batchId">
              <el-select
                v-model="formData.batchId"
                :placeholder="t('common.selectTextPlaceholder') + t('interview.fields.batchId')"
                @change="getInterviewAvailableTime"
              >
                <el-option
                  v-for="(item, index) in batchOptions"
                  :key="index"
                  :label="item.batchName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('interview.fields.interviewDate')" prop="interviewDate">
              <el-date-picker
                class="!w-1/1"
                v-model="formData.interviewDate"
                type="date"
                value-format="x"
                :placeholder="
                  t('common.selectTextPlaceholder') + t('interview.fields.interviewDate')
                "
                :disabled-date="disableInterviewDate"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="t('interview.fields.studentLimit')" prop="studentLimit">
              <el-input-number
                v-model="formData.studentLimit"
                :placeholder="t('common.inputTextPlaceholder') + t('interview.fields.studentLimit')"
                class="better-number-input !w-1/1"
                :controls="false"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="t('interview.fields.studentLimitAm')" prop="studentLimitAm">
              <el-input-number
                v-model="formData.studentLimitAm"
                :placeholder="
                  t('common.inputTextPlaceholder') + t('interview.fields.studentLimitAm')
                "
                class="better-number-input !w-1/1"
                :controls="false"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="t('interview.fields.studentLimitPm')" prop="studentLimitPm">
              <el-input-number
                v-model="formData.studentLimitPm"
                :placeholder="
                  t('common.inputTextPlaceholder') + t('interview.fields.studentLimitPm')
                "
                class="better-number-input !w-1/1"
                :controls="false"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="t('interview.fields.interviewDuration')" prop="interviewDuration">
              <el-input-number
                v-model="formData.interviewDuration"
                :placeholder="
                  t('common.inputTextPlaceholder') + t('interview.fields.interviewDuration')
                "
                class="better-number-input !w-1/1"
                :controls="false"
                :min="1"
              >
                <template #suffix>
                  <span>{{ t('interview.form.min') }}</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!--          <el-col :span="12">-->
          <!--            <el-form-item :label="t('interview.fields.interviewGap')" prop="interviewGap">-->
          <!--              <el-input-number-->
          <!--                v-model="formData.interviewGap"-->
          <!--                :placeholder="t('common.inputTextPlaceholder') + t('interview.fields.interviewGap')"-->
          <!--                class="better-number-input !w-1/1"-->
          <!--                :controls="false"-->
          <!--                :min="0"-->
          <!--              >-->
          <!--                <template #suffix>-->
          <!--                  <span>{{ t('interview.form.min') }}</span>-->
          <!--                </template>-->
          <!--              </el-input-number>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item :label="t('interview.fields.interviewTime')" prop="interviewStartTime">
              <el-time-picker
                v-model="interviewTime"
                is-range
                arrow-control
                value-format="HH:mm:ss"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('interview.fields.amBreakTime')" prop="amBreakStartTime">
              <el-time-picker
                v-model="amBreakTime"
                is-range
                arrow-control
                value-format="HH:mm:ss"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="t('interview.fields.launchTime')" prop="launchStartTime">
              <el-time-picker
                v-model="launchTime"
                is-range
                arrow-control
                value-format="HH:mm:ss"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('interview.fields.pmBreakTime')" prop="pmBreakStartTime">
              <el-time-picker
                v-model="pmBreakTime"
                is-range
                arrow-control
                value-format="HH:mm:ss"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="!showTips">
        <CardTitle :title="t('interview.form.tips')" />
        <el-table :data="schedule" max-height="450">
          <el-table-column type="index" />
          <el-table-column prop="daytime" :label="t('interviewSlot.fields.daytime')" />
          <el-table-column prop="startTime" :label="t('interviewSlot.fields.startTime')" />
          <el-table-column prop="endTime" :label="t('interviewSlot.fields.endTime')" />
        </el-table>
      </div>
    </div>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InterviewApi, InterviewVO } from '@/api/recruit/interview'
import { FormRules } from 'element-plus'
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import { InterviewSlotVO } from '@/api/recruit/interviewslot'

/** 面试 表单 */
defineOptions({ name: 'InterviewForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  batchId: undefined,
  interviewDate: undefined,
  studentLimit: undefined,
  studentLimitAm: undefined,
  studentLimitPm: undefined,
  interviewDuration: undefined,
  interviewGap: 0,
  interviewStartTime: '09:00:00',
  interviewEndTime: '17:00:00',
  launchStartTime: '11:30:00',
  launchEndTime: '13:30:00',
  amBreakStartTime: '10:00:00',
  amBreakEndTime: '10:30:00',
  pmBreakStartTime: '14:30:00',
  pmBreakEndTime: '15:00:00',
  status: undefined,
  interviewTimes: undefined,
  groups: undefined,
  remark: undefined
})
const formRules = reactive<FormRules>({
  batchId: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.batchId'),
      trigger: 'change'
    }
  ],
  interviewDate: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.interviewDate'),
      trigger: 'change'
    }
  ],
  studentLimit: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('interview.fields.studentLimit'),
      trigger: 'blur'
    }
  ],
  studentLimitAm: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('interview.fields.studentLimitAm'),
      trigger: 'blur'
    }
  ],
  studentLimitPm: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('interview.fields.studentLimitPm'),
      trigger: 'blur'
    }
  ],
  interviewDuration: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('interview.fields.interviewDuration'),
      trigger: 'blur'
    }
  ],
  interviewGap: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('interview.fields.interviewGap'),
      trigger: 'blur'
    }
  ],
  interviewStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.interviewTime'),
      trigger: 'change'
    }
  ],
  interviewEndTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.interviewTime'),
      trigger: 'change'
    }
  ],
  launchStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.launchTime'),
      trigger: 'change'
    }
  ],
  launchEndTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.launchTime'),
      trigger: 'change'
    }
  ],
  amBreakStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.amBreakTime'),
      trigger: 'change'
    }
  ],
  amBreakEndTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.amBreakTime'),
      trigger: 'change'
    }
  ],
  pmBreakStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.pmBreakTime'),
      trigger: 'change'
    }
  ],
  pmBreakEndTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('interview.fields.pmBreakTime'),
      trigger: 'change'
    }
  ]
})
const formRef = ref() // 表单 Ref

const interviewTime = computed({
  get() {
    return [formData.value.interviewStartTime, formData.value.interviewEndTime]
  },
  set(value) {
    formData.value.interviewStartTime = value[0] ?? undefined
    formData.value.interviewEndTime = value[1] ?? undefined
  }
})

const amBreakTime = computed({
  get() {
    return [formData.value.amBreakStartTime, formData.value.amBreakEndTime]
  },
  set(value) {
    formData.value.amBreakStartTime = value[0] ?? undefined
    formData.value.amBreakEndTime = value[1] ?? undefined
  }
})

const pmBreakTime = computed({
  get() {
    return [formData.value.pmBreakStartTime, formData.value.pmBreakEndTime]
  },
  set(value) {
    formData.value.pmBreakStartTime = value[0] ?? undefined
    formData.value.pmBreakEndTime = value[1] ?? undefined
  }
})

const launchTime = computed({
  get() {
    return [formData.value.launchStartTime, formData.value.launchEndTime]
  },
  set(value) {
    formData.value.launchStartTime = value[0] ?? undefined
    formData.value.launchEndTime = value[1] ?? undefined
  }
})

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  getBatchSelectOptions()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InterviewApi.getInterview(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as InterviewVO
    if (formType.value === 'create') {
      await InterviewApi.createInterviewWithSlot({
        ...data,
        slots: schedule.value
      })
      message.success(t('common.createSuccess'))
    } else {
      await InterviewApi.updateInterview(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    batchId: undefined,
    interviewDate: undefined,
    studentLimit: undefined,
    studentLimitAm: undefined,
    studentLimitPm: undefined,
    interviewDuration: undefined,
    interviewGap: 0,
    interviewStartTime: '09:00:00',
    interviewEndTime: '17:00:00',
    launchStartTime: '11:30:00',
    launchEndTime: '13:30:00',
    amBreakStartTime: '10:00:00',
    amBreakEndTime: '10:30:00',
    pmBreakStartTime: '14:30:00',
    pmBreakEndTime: '15:00:00',
    status: undefined,
    interviewTimes: undefined,
    groups: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}

const batchOptions = ref<BatchVO[]>([])
const getBatchSelectOptions = async () => {
  batchOptions.value = await BatchApi.getSelectList()
}

const currentBatch = ref<BatchVO>()

const disableInterviewDate = (time: Date) => {
  if (currentBatch.value) {
    // 处于currentBatch.value.recruitStartTime 和 currentBatch.value.recruitEndTime之外的日期不可选
    const startTime = new Date(currentBatch.value.recruitStartTime)
    const endTime = new Date(currentBatch.value.recruitEndTime)
    // 将 startTime 的时间设置为该日的开始
    startTime.setHours(0, 0, 0, 0)
    // 将 endTime 的时间设置为该日的结束
    endTime.setHours(23, 59, 59, 999)
    return time < startTime || time > endTime
  } else {
    // 如果没有选择计划，则所有日期都不可选
    return true
  }
}

// 计划改变 获取当前计划详情 并 清空已选时间
const getInterviewAvailableTime = () => {
  currentBatch.value = batchOptions.value.find((item) => item.id === formData.value.batchId)
  // 清空已选时间
  formData.value.interviewDate = undefined
}

const schedule = ref<Partial<InterviewSlotVO>[]>([])
const showTips = ref(true)

const timeToSeconds = (time) => {
  const [hours, minutes, seconds] = time.split(':').map(Number)
  return hours * 3600 + minutes * 60 + seconds
}

const secondsToTime = (seconds) => {
  const hours = String(Math.floor(seconds / 3600)).padStart(2, '0')
  const minutes = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0')
  const secs = String(seconds % 60).padStart(2, '0')
  return `${hours}:${minutes}:${secs}`
}

watchEffect(() => {
  // 检查所有用到的值 如果有空的则不计算
  if (
    !formData.value.interviewDuration ||
    // (!formData.value.interviewGap && formData.value.interviewGap !== 0) ||
    !formData.value.interviewStartTime ||
    !formData.value.interviewEndTime ||
    !formData.value.launchStartTime ||
    !formData.value.launchEndTime ||
    !formData.value.amBreakStartTime ||
    !formData.value.amBreakEndTime ||
    !formData.value.pmBreakStartTime ||
    !formData.value.pmBreakEndTime
  ) {
    showTips.value = true
    schedule.value = []
    return
  }
  showTips.value = false
  // 将时长转换为秒
  const interviewDurationInSeconds = formData.value.interviewDuration * 60
  const breakDurationInSeconds = formData.value.interviewGap * 60

  const startWorkingTime = timeToSeconds(formData.value.interviewStartTime)
  const endWorkingTime = timeToSeconds(formData.value.interviewEndTime)
  const lunchStart = timeToSeconds(formData.value.launchStartTime)
  const lunchEnd = timeToSeconds(formData.value.launchEndTime)

  const amBreakStart = timeToSeconds(formData.value.amBreakStartTime)
  const amBreakEnd = timeToSeconds(formData.value.amBreakEndTime)
  const pmBreakStart = timeToSeconds(formData.value.pmBreakStartTime)
  const pmBreakEnd = timeToSeconds(formData.value.pmBreakEndTime)

  let morningSlots: Partial<InterviewSlotVO>[] = []
  let afternoonSlots: Partial<InterviewSlotVO>[] = []

  // 生成上午排程
  let currentTime = startWorkingTime
  while (currentTime + interviewDurationInSeconds <= lunchStart) {
    const start = secondsToTime(currentTime)
    const end = secondsToTime(currentTime + interviewDurationInSeconds)
    if (
      (currentTime < amBreakStart && currentTime + interviewDurationInSeconds <= amBreakStart) ||
      (currentTime >= amBreakEnd && currentTime + interviewDurationInSeconds > amBreakEnd)
    ) {
      morningSlots.push({
        daytime: '上午',
        startTime: start,
        endTime: end
      })
      currentTime += interviewDurationInSeconds + breakDurationInSeconds
    } else {
      currentTime += 1
    }
  }

  // 生成下午排程
  currentTime = lunchEnd
  while (currentTime + interviewDurationInSeconds <= endWorkingTime) {
    const start = secondsToTime(currentTime)
    const end = secondsToTime(currentTime + interviewDurationInSeconds)
    if (
      (currentTime < pmBreakStart && currentTime + interviewDurationInSeconds <= pmBreakStart) ||
      (currentTime >= pmBreakEnd && currentTime + interviewDurationInSeconds > pmBreakEnd)
    ) {
      afternoonSlots.push({
        daytime: '下午',
        startTime: start,
        endTime: end
      })
      currentTime += interviewDurationInSeconds + breakDurationInSeconds
    } else {
      currentTime += 1
    }
  }

  // 合并上午和下午的排程
  schedule.value = [...morningSlots, ...afternoonSlots]
})
</script>
